import { View, Button as TaroButton } from '@tarojs/components';
import classNames from 'classnames';
import { useMemo, useState } from 'react';
import theme from '@/theme';
import Loading from '../Loading';
import LinearGradient from '../LinearGradient';
import Text from '../Text';
import './index.scss';

const RootView = ({ openType, style, className, ...props }) => {
  if (process.env.TARO_ENV === 'weapp' && openType) {
    return <TaroButton openType={openType} style={style} className={classNames('button-clean', className)} {...props} />;
  }
  return <View style={style} className={className} {...props} />;
};

const Button = ({
  type = 'default',
  color = theme.button.color,
  colorAngle = 90,
  radiusType = theme.button.radiusType,
  size = theme.button.size,
  plain = theme.button.plain,
  openType,
  style,
  disabled,
  loading,
  className,
  onClick,
  renderContent,
  children,
}) => {
  const linearGradient = color instanceof Array;

  plain = linearGradient ? false : plain;

  const [viewStyle, textStyle] = useMemo(() => {
    if (type !== 'default') {
      return [];
    }
    const styles = [{}, {}];
    if (color) {
      if (linearGradient) {
      } else if (plain) {
        styles[1].color = color;
        styles[0].borderColor = color;
      } else {
        styles[0].borderColor = color;
        styles[0].backgroundColor = color;
      }
    }

    return styles;
  }, [color, linearGradient, plain, type]);

  return (
    <RootView
      {...(disabled || !onClick ? {} : { onClick })}
      className={classNames(
        'pd-button',
        !plain && 'pd-button--' + type,
        plain && 'pd-button--plain pd-button--plain-' + type,
        'pd-button--' + radiusType,
        disabled && 'pd-button--disabled',
        linearGradient && 'pd-button--linear',
        'pd-button--' + size,
        className,
      )}
      openType={openType}
      style={{
        ...viewStyle,
        ...style,
      }}
      hoverClass='pd-button--hover'
      hoverStyle={!disabled && { opacity: 0.8 }}>
      {linearGradient && <LinearGradient colors={color} useAngle angle={colorAngle} className='absolute inset-0' />}
      {loading && (
        <Loading
          color={plain || (type === 'default' && !color) ? 'dark' : 'blank'}
          size={theme.button.sizes[size].fs * 1.4}
          className='pd-button__loading'
        />
      )}
      {renderContent || (
        <Text
          {...(plain ? { type } : {})}
          {...(type === 'default' ? { color: 1 } : {})}
          numberOfLines={1}
          className={classNames(
            'pd-button__text',
            ((!plain && type !== 'default') || color) && 'pd-button-c-white',
            'pd-button--fs-' + size,
          )}
          style={textStyle}>
          {children}
        </Text>
      )}
    </RootView>
  );
};

export default Button;
